package com.bakery.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bakery.dto.SalesOrderDTO;
import com.bakery.entity.*;
import com.bakery.mapper.SalesOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 销售订单Service
 *
 * @author bakery
 */
@Service
public class SalesOrderService extends ServiceImpl<SalesOrderMapper, SalesOrder> {
    
    @Autowired
    private EmployeeService employeeService;
    
    @Autowired
    private BreadService breadService;
    
    @Autowired
    private SalesOrderItemService salesOrderItemService;
    
    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        return "SO" + System.currentTimeMillis();
    }
    
    /**
     * 创建销售订单
     */
    @Transactional(rollbackFor = Exception.class)
    public void createOrder(SalesOrderDTO dto) {
        Employee currentEmployee = employeeService.getCurrentEmployee();
        
        // 验证订单明细
        if (dto.getItems() == null || dto.getItems().isEmpty()) {
            throw new RuntimeException("订单明细不能为空");
        }
        
        // 计算订单总金额并验证库存
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<SalesOrderItem> items = new ArrayList<>();
        
        for (SalesOrderDTO.SalesOrderItemDTO itemDTO : dto.getItems()) {
            Bread bread = breadService.getById(itemDTO.getBreadId());
            if (bread == null) {
                throw new RuntimeException("面包不存在");
            }
            
            if (bread.getStatus() == 0) {
                throw new RuntimeException(bread.getName() + " 已下架");
            }
            
            if (bread.getStock() < itemDTO.getQuantity()) {
                throw new RuntimeException(bread.getName() + " 库存不足");
            }
            
            BigDecimal subtotal = bread.getPrice().multiply(new BigDecimal(itemDTO.getQuantity()));
            totalAmount = totalAmount.add(subtotal);
            
            SalesOrderItem item = new SalesOrderItem();
            item.setBreadId(bread.getId());
            item.setBreadName(bread.getName());
            item.setPrice(bread.getPrice());
            item.setQuantity(itemDTO.getQuantity());
            item.setSubtotal(subtotal);
            
            items.add(item);
        }
        
        // 创建订单
        SalesOrder order = new SalesOrder();
        order.setOrderNo(generateOrderNo());
        order.setTotalAmount(totalAmount);
        order.setPaymentMethod(dto.getPaymentMethod());
        order.setEmployeeId(currentEmployee.getId());
        order.setSaleTime(LocalDateTime.now());
        order.setStatus(1);
        order.setRemark(dto.getRemark());
        
        save(order);
        
        // 保存订单明细
        for (SalesOrderItem item : items) {
            item.setOrderId(order.getId());
            salesOrderItemService.save(item);
            
            // 扣减库存
            breadService.deductStock(item.getBreadId(), item.getQuantity(), currentEmployee.getId());
        }
    }
    
    /**
     * 分页查询订单
     */
    public Page<SalesOrder> getOrderPage(Integer page, Integer size, String orderNo, 
                                         LocalDateTime startTime, LocalDateTime endTime, Integer status) {
        LambdaQueryWrapper<SalesOrder> wrapper = new LambdaQueryWrapper<>();
        
        if (StrUtil.isNotBlank(orderNo)) {
            wrapper.like(SalesOrder::getOrderNo, orderNo);
        }
        
        if (startTime != null) {
            wrapper.ge(SalesOrder::getSaleTime, startTime);
        }
        
        if (endTime != null) {
            wrapper.le(SalesOrder::getSaleTime, endTime);
        }
        
        if (status != null) {
            wrapper.eq(SalesOrder::getStatus, status);
        }
        
        wrapper.orderByDesc(SalesOrder::getSaleTime);
        
        Page<SalesOrder> orderPage = page(new Page<>(page, size), wrapper);
        
        // 补充订单明细和员工信息
        for (SalesOrder order : orderPage.getRecords()) {
            // 查询订单明细
            LambdaQueryWrapper<SalesOrderItem> itemWrapper = new LambdaQueryWrapper<>();
            itemWrapper.eq(SalesOrderItem::getOrderId, order.getId());
            order.setItems(salesOrderItemService.list(itemWrapper));
            
            // 查询员工姓名
            Employee employee = employeeService.getById(order.getEmployeeId());
            if (employee != null) {
                order.setEmployeeName(employee.getName());
            }
        }
        
        return orderPage;
    }
    
    /**
     * 获取订单详情
     */
    public SalesOrder getOrderDetail(Long id) {
        SalesOrder order = getById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 查询订单明细
        LambdaQueryWrapper<SalesOrderItem> itemWrapper = new LambdaQueryWrapper<>();
        itemWrapper.eq(SalesOrderItem::getOrderId, order.getId());
        order.setItems(salesOrderItemService.list(itemWrapper));
        
        // 查询员工姓名
        Employee employee = employeeService.getById(order.getEmployeeId());
        if (employee != null) {
            order.setEmployeeName(employee.getName());
        }
        
        return order;
    }
    
    /**
     * 取消订单（仅店长可操作）
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long id, String reason) {
        Employee currentEmployee = employeeService.getCurrentEmployee();
        
        if (!"MANAGER".equals(currentEmployee.getRole())) {
            throw new RuntimeException("只有店长可以取消订单");
        }
        
        SalesOrder order = getById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        if (order.getStatus() == 0) {
            throw new RuntimeException("订单已取消");
        }
        
        // 查询订单明细
        LambdaQueryWrapper<SalesOrderItem> itemWrapper = new LambdaQueryWrapper<>();
        itemWrapper.eq(SalesOrderItem::getOrderId, order.getId());
        List<SalesOrderItem> items = salesOrderItemService.list(itemWrapper);
        
        // 恢复库存
        for (SalesOrderItem item : items) {
            breadService.restoreStock(item.getBreadId(), item.getQuantity(), currentEmployee.getId());
        }
        
        // 更新订单状态
        order.setStatus(0);
        order.setRemark(StrUtil.isBlank(reason) ? "店长取消订单" : reason);
        updateById(order);
    }
    
    /**
     * 销售统计
     */
    public Map<String, Object> getSalesStatistics(LocalDateTime startTime, LocalDateTime endTime) {
        LambdaQueryWrapper<SalesOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SalesOrder::getStatus, 1); // 只统计正常订单
        
        if (startTime != null) {
            wrapper.ge(SalesOrder::getSaleTime, startTime);
        }
        
        if (endTime != null) {
            wrapper.le(SalesOrder::getSaleTime, endTime);
        }
        
        List<SalesOrder> orders = list(wrapper);
        
        // 统计总销售额
        BigDecimal totalSales = orders.stream()
                .map(SalesOrder::getTotalAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        // 统计订单数量
        int orderCount = orders.size();
        
        // 统计热销商品
        Map<String, Integer> breadSalesMap = new HashMap<>();
        for (SalesOrder order : orders) {
            LambdaQueryWrapper<SalesOrderItem> itemWrapper = new LambdaQueryWrapper<>();
            itemWrapper.eq(SalesOrderItem::getOrderId, order.getId());
            List<SalesOrderItem> items = salesOrderItemService.list(itemWrapper);
            
            for (SalesOrderItem item : items) {
                breadSalesMap.merge(item.getBreadName(), item.getQuantity(), Integer::sum);
            }
        }
        
        // 转换为热销排行榜（Top 10）
        List<Map<String, Object>> topBreadList = breadSalesMap.entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .limit(10)
                .map(entry -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("breadName", entry.getKey());
                    map.put("salesCount", entry.getValue());
                    return map;
                })
                .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("totalSales", totalSales);
        result.put("orderCount", orderCount);
        result.put("topBreadList", topBreadList);
        
        return result;
    }
}

